import resources.Constants;

import registnet.dao.SectionConfigurationPeer;
import registnet.dao.SectionConfiguration;
import registnet.dao.UnitPeer;

String _add = bundle.getProperty("registnet.module.data_management.actions.menu.add");
String _edit = bundle.getProperty("registnet.module.data_management.actions.menu.edit");
String _delete = bundle.getProperty("registnet.module.data_management.actions.menu.delete");
String _save = bundle.getProperty("registnet.module.data_management.macro.colleges.form.save");
String _cancel = bundle.getProperty("registnet.module.data_management.macro.colleges.form.cancel");

SectionConfigurationPeer scp = new SectionConfigurationPeer();
SectionConfiguration sc = new SectionConfiguration();

String _icon_add = bundle.getProperty("registnet.icons.add");
String _icon_edit = bundle.getProperty("registnet.icons.edit");
String _icon_delete = bundle.getProperty("registnet.icons.delete");

List data = new Vector();


boolean isShowingInfo;


/* [start]	prepares the tree */
ArrayList alc = new ArrayList();
SimpleTreeNode root = new SimpleTreeNode("ROOT", alc);
/* [end] */


/* [start]	defines the renderer for the tree */
public class MyTreeitemRenderer implements TreeitemRenderer {
	public void render(Treeitem item, Object data) throws Exception {
		String str = (String)data.getData();
		Treerow tr = null;
		Treecell tc = new Treecell(str);
		if(item.getTreerow()==null){
			tr = new Treerow();
			tr.setParent(item);
		}else{
			tr = item.getTreerow(); 
			tr.getChildren().clear();
		}
		tc.setParent(tr);
		item.setOpen(false);
	}
}
/* [end] */


/* [start]	retrieves the section configurations and places them on the tree; */
public void retrieveObjects(){
	alc.clear();
	data = scp.getSectionConfigurationsByUnit(new UnitPeer().getUnitId(_office));
	for(int i=0; i<data.size(); i++){
		SimpleTreeNode stnSectionConfiguration = new SimpleTreeNode(data.get(i).getSectionConfigurationName(), new ArrayList());
		alc.add(stnSectionConfiguration);
	}
	SimpleTreeModel stm = new SimpleTreeModel(root);
	instance_tree.setModel(stm);
	instance_tree.setTreeitemRenderer(new MyTreeitemRenderer());
}
/* [end] */


/* [start]	defines an event listener for the items on the tree;
			when the item is selected, its info is displayed */
private class SelectEventListener implements EventListener {
	public SelectEventListener (){}
	public void onEvent(Event event) throws UiException {
		showInfo();
	}
}
/* [end] */


/* [start]	defines an event listener for the cancel button;
			when fired, it deselects the items on the tree */
private class CancelEventListener implements EventListener {
	public SubmitEventListener (){}
	public void onEvent(Event event) throws UiException {
		instance_tree.clearSelection();
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}
/* [end] */


/* [start]	defines an event listener for the submit button */
private class SubmitEventListener implements EventListener {
	String submitType;
	public SubmitEventListener (String submitType){
		this.submitType = submitType; 
	}
	public void onEvent(Event event) throws UiException {
		if(this.submitType.equals(_add))
			createNewSectionConfiguration();
		else if (this.submitType.equals(_edit))
			editSectionConfiguration();
	}
}
/* [end] */


void showInfo(){
	isShowingInfo = true;
	if (contents.getFirstChild() != null){
		contents.removeChild(contents.getFirstChild());
	}
	
	try{
		if (instance_tree.getSelectedCount() == 1){
			sc = scp.getSectionConfiguration(instance_tree.getSelectedItem().getLabel(), new UnitPeer().getUnitId(_office));
			Component show_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_form.zul", contents, null);
			title.setValue(sc.getSectionConfigurationName());
			show_instance_form.getFellow("configuration_name_l").setValue(sc.getSectionConfigurationName());
			show_instance_form.getFellow("save_btn").detach();
			show_instance_form.getFellow("cancel_btn").detach();
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + "Section Configuration" + " " + "selected");
		else
			title.setValue("");
	}catch (Exception e) { title.setValue(""); }
}


/* [start]	displays the form for creating a new or editing an existing entry */
void showForm(String action){
	isShowingInfo = false;
	try{
		contents.removeChild(contents.getFirstChild());
	} catch (Exception e) {}
	if (action.equals(_edit)){
		if(instance_tree.getSelectedCount() == 1){
			Component edit_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_form.zul", contents, null);
			title.setValue(_edit + " " + sc.getSectionConfigurationName());
			edit_instance_form.getFellow("configuration_name").setValue(sc.getSectionConfigurationName());
			edit_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
			edit_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
		}
		else{
			alert("Select one Section Configuration");
		}
	}	
	else if (action.equals(_add)){
		Component add_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/section_configuration_form.zul", contents, null);
		title.setValue(_add + " " + "Section Configuration");
		instance_tree.clearSelection();
		add_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
		add_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
	}
}
/* [end] */



/* [start]	creates a new entry;
			updates the tree */
void createNewSectionConfiguration(){
	if (isValid()){
		if (scp.createNewSectionConfiguration(configuration_name.value, new UnitPeer().getUnitId(_office)) != null){
			data.add(scp.getSectionConfiguration(configuration_name.value, new UnitPeer().getUnitId(_office)));
			title.setValue("Add Section Configuration Successful");
			SimpleTreeNode stnConfiguration = new SimpleTreeNode(configuration_name.value, new ArrayList());
			alc.add(stnConfiguration);
			instance_tree.setModel(instance_tree.getModel());		
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		}
		else
			alert("Chech information supplied");
	}
	else{
		alert("Chech information supplied");
	}
}
/* [end] */



/* [start]	edits an existing entry;
			updates the tree */
void editSectionConfiguration(){
	if (isValid()){
		try{
			if (scp.updateSectionConfiguration(sc.getSectionConfigurationId(), configuration_name.value)){
				data.set(instance_tree.getSelectedItem().indexOf(), scp.getSectionConfiguration(configuration_name.value, new UnitPeer().getUnitId(_office)));
				SimpleTreeNode stnConfiguration = new SimpleTreeNode(configuration_name.value, new ArrayList());
				alc.set(instance_tree.getSelectedItem().indexOf(), stnConfiguration);
				instance_tree.clearSelection();
				instance_tree.setModel(instance_tree.getModel());
				title.setValue("Edit Section Configuration Successful");
			}
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		} catch (Exception e) { alert("Check information supplied"); }
	}
	else{
		alert("Check information supplied");
	}
}
/* [end] */



/* [start]	deletes an entry */
void delete(){
	if(instance_tree.getSelectedCount() != 0){
		int isConfirmed = Messagebox.show("Proceed", "Delete" + " " + "Section Configuration", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
		if (isConfirmed == Messagebox.YES){
			boolean isError = false;
			int errorCount = 0;
			Iterator i = instance_tree.getSelectedItems().iterator();
			int counter = 0;
			while(i.hasNext()){
				Treeitem treeitem = i.next(); 
				if (scp.deleteSectionConfiguration(treeitem.getLabel(), new UnitPeer().getUnitId(_office))){
					alc.remove(treeitem.indexOf() - counter);
					data.remove(treeitem.indexOf() - counter);
					counter++;
				}
				else{
					isError = true;
					errorCount++;
				}				
			}
			instance_tree.setModel(instance_tree.getModel());
			if (isError){ 
				alert("Delete" + " " + "failed" + ": " + errorCount + " " + "Section Configuration");
				title.setValue("Delete" + " " + "Section Configuration" + " " + "failed");
			}
			
			else{
				title.setValue("Delete" + " " + "Section Configuration" + " " + "successful");
				if (contents.getFirstChild() != null){
					contents.removeChild(contents.getFirstChild());
				}
			}
		}			
	}
	else{
		alert("Select one Section Configuration");
	}
}
/* [end] */



boolean isValid(){
	if (configuration_name.value.trim().length() == 0)
		return false;
	return true;
}


void configure(){
	try{
		if (instance_tree.getSelectedCount() == 1){
			sc = scp.getSectionConfiguration(instance_tree.getSelectedItem().getLabel(), new UnitPeer().getUnitId(_office));
			
			
			if(!map_tab.containsKey(sc.getSectionConfigurationName())){
			
				Tabbox stage = section_configuration_win.getParent().getParent().getParent();
				
				Tabs tabs = stage.getTabs();
				Tab tab = new Tab(sc.getSectionConfigurationName());
				tab.setClosable(true);
				tab.setParent(tabs);
				tab.addEventListener("onClose", new CloseTabEventListener(sc.getSectionConfigurationName()));
				
				Tabpanels tabpanels = stage.getTabpanels();
				Tabpanel tabpanel = new Tabpanel();
				tabpanel.setSclass("background_light_blue");
				tabpanel.setParent(tabpanels);
				stage.setSelectedPanel(tabpanel);
				
				map_tab.put(sc.getSectionConfigurationName(), tab);
				
				HashMap map = new HashMap();
				map.put("configId", sc.getSectionConfigurationId());
				Component win = Executions.createComponents("../../WEB-INF/macros/data_management/configuration_sections.zul", tabpanel, map);
			}
			
			else
				map_tab.get(sc.getSectionConfigurationName()).setSelected(true);
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + "Section Configuration" + " " + "selected");
		else
			title.setValue("");
	}catch (Exception e) { e.printStackTrace(); title.setValue(""); }
}